/*
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\TodoList\QuotaAdjustment\AdjustApproveForm.tsx
 * @Date: 2021-09-27 15:30:46
 * @LastEditTime: 2023-05-09 09:28:38
 */

import React from 'react'
import { http, IUdFormItem, UdForm, validators } from '@/lib'
import { Input, Select } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import ProcessList from '@/components/ProcessList/index'
import todoApi from '@/apis/TodoList/index'
import approveModal from '@/components/ApproveModal'
import { WithToolbar } from '@/components/PhotoView'
import TextArea from 'antd/lib/input/TextArea'
const { Option } = Select
interface IProps {
  record: any
  todoType?: any
  refresh?: any
}
interface IState {
  recordDetail: any
  approverList?: any
}
export default class ApproveForm extends React.Component<IProps, IState> {
  private labelCol: any = { span: 6 }
  private MODIFY_TYPE_ENUM: any = { UP: '调增', DOWN: '调减', ADJUST: '调剂', READJUST: '客户间调整', ADD: '导入' }
  private READJUST_ITEMS: IUdFormItem[] = [
    { id: 'belongAreaName', label: '调入方片区', render: <Input readOnly /> },
    { id: 'dealerNameRe', label: '调入方客户', render: <Input readOnly /> },
    { id: 'modifyBeforeQuota', label: '调入方调整前考核阶段剩余配额', render: <Input readOnly /> },
    { id: 'modifyAfterQuota', label: '调入方调整后考核阶段剩余配额', render: <Input readOnly /> },
    { id: 'belongAreaNameIn', label: '调出方片区', render: <Input readOnly /> },
    { id: 'dealerNameIn', label: '调出方客户', render: <Input readOnly /> },
    { id: 'modifyBeforeQuotaIn', label: '调出方调整前考核阶段剩余配额', render: <Input readOnly /> },
    { id: 'modifyAfterQuotaIn', label: '调出方调整后考核阶段剩余配额', render: <Input readOnly /> },
  ]
  private UPORDOWN_ITEMS: any = [
    { id: 'modifyBeforeQuota', label: '调整前考核阶段剩余配额', render: <Input readOnly /> },
    { id: 'modifyAfterQuota', label: '调整后考核阶段剩余配额', render: <Input readOnly /> },
  ]
  private ADJUST_ITEMS: any = [
    { id: 'modifyBeforeQuota', label: '调整前考核阶段剩余配额', render: <Input readOnly /> },
    { id: 'modifyAfterQuota', label: '调整后考核阶段剩余配额', render: <Input readOnly /> },
    { id: 'modifyBeforeQuotaSum', label: '调整前年度剩余配额', render: <Input readOnly /> },
    { id: 'modifyAfterQuotaSum', label: '调整后年度剩余配额', render: <Input readOnly /> },
  ]
  private PLAN_TYPE_ENUM: any = {
    0: '计划内',
    1: '计划外',
  }
  private form: WrappedFormUtils
  private record = this.props.record || {}
  private todoType = this.props.todoType
  private refresh = this.props.refresh
  private roleIds = []
  private isLastApprover = false // 是否最后审批人

  constructor(props: IProps, state: IState) {
    super(props)
    this.state = {
      approverList: [],
      recordDetail: { modifyType: null },
    }
  }
  componentDidMount() {
    this.getFromDetail()
  }

  //获取详情
  private getFromDetail = () => {
    const {
      record: { traceCode: businessKey, brandCode },
    } = this.props
    let params = { businessKey, brandCode }
    http.get(todoApi.getAdjustApproveDetail, { params }).then(res => {
      let values = { ...res.data }
      values.term =
        values.quotaBeginTime && values.quotaEndTime ? `${values.quotaBeginTime}-${values.quotaEndTime}` : ''
      values.modifyTypeText = this.MODIFY_TYPE_ENUM[values.modifyType]
      values.dealerNameRe = values.dealerName
      values.planTypeText = this.PLAN_TYPE_ENUM[values.planType]
      this.setState({ recordDetail: values }, () => {
        if (this.todoType === 1) {
          this.getNextApprover()
        }
      })
    })
  }

  private getNextApprover = async () => {
    let { isCross } = this.state.recordDetail
    try {
      const approverRoles = await http.get(todoApi.getAdjustNextApprove, {
        params: { taskId: this.record.taskDefId, isCross },
      })
      if (approverRoles.data && approverRoles.data[0] && approverRoles.data[0]?.roleIds?.length > 0) {
        // 有下一级审批人才去选择，用于判断是否最后审批人
        this.roleIds = approverRoles.data[0].roleIds
        const params = { ids: approverRoles.data[0].roleIds }
        const nextApprover = await http.post(todoApi.NextApproverList, params)
        const approverList = nextApprover.data.map(({ id: value, realName: title }) => ({ value, title }))
        this.setState({ approverList })
      } else {
        this.isLastApprover = true
      }
    } catch {}
  }

  private onOk = e => {
    let { isCross } = this.state.recordDetail
    const modalItems = !this.isLastApprover
      ? [
          {
            id: 'approveUserIds',
            label: '下一审批人',
            rules: [validators.required],
            render: () => {
              return (
                <Select mode="multiple" showSearch={true} optionFilterProp="children">
                  {this.state.approverList.map(item => (
                    <Option key={item.value} value={item.value}>
                      {item.title}
                    </Option>
                  ))}
                </Select>
              )
            },
          },
        ]
      : []
    approveModal({
      e,
      modalItems,
      isCross,
      taskId: this.record.taskDefId,
      roleIds: this.roleIds,
      refresh: this.refresh,
      todoType: this.todoType,
    })
  }
  render() {
    const {
      recordDetail: { modifyType },
    } = this.state
    let extendItems = []
    if (modifyType === 'READJUST') {
      extendItems = this.READJUST_ITEMS
    } else if (modifyType === 'ADJUST') {
      extendItems = this.ADJUST_ITEMS
    } else {
      extendItems = this.UPORDOWN_ITEMS
    }
    let items: IUdFormItem[] = [
      { id: 'brandName', label: '品牌公司', render: <Input readOnly /> },
      { id: 'prodBarname', label: '配额品项', render: <Input readOnly /> },
      { id: 'stageYear', label: '考核年度', render: <Input readOnly /> },
      { id: 'stageName', label: '考核阶段', render: <Input readOnly /> },
      { id: 'term', label: '配额有效期', render: <Input readOnly /> },
      { id: 'dealerName', label: '客户名称', render: <Input readOnly /> },
      { label: '计划类型', id: 'planTypeText', render: () => <Input readOnly /> },
      { id: 'modifyTypeText', label: '调整类型', render: <Input readOnly /> },
      ...extendItems,
      { id: 'modifyQuota', label: '调整数量', render: <Input readOnly /> },
      { id: 'remark', label: '备注信息', render: <TextArea rows={3} readOnly /> },
      {
        id: 'file',
        label: '附件',
        render: (
          <>
            <WithToolbar
              imagesList={this.state?.recordDetail?.['quotaApplyDetailFileRespVoList'] || []}
              type="processList"
            />
          </>
        ),
      },
    ]
    return (
      <>
        <UdForm
          key={Date.now()}
          getForm={form => (this.form = form)}
          labelCol={this.labelCol}
          items={items}
          values={this.state.recordDetail}
        />
        <ProcessList record={this.state.recordDetail} />
      </>
    )
  }
}
